import { ref } from 'vue';

import { StorageManager } from '@vben-core/shared/cache';

import { defineStore } from 'pinia';

import { messageApi } from '#/api';
import { SOCKET_IP } from '#/constant';

// 你可以对 `defineStore()` 的返回值进行任意命名，但最好使用 store 的名字，同时以 `use` 开头且以 `Store` 结尾。(比如 `useUserStore`，`useCartStore`，`useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。

const storageManager = new StorageManager({
  prefix: '',
  storageType: 'sessionStorage',
});
export const useWebSocketStore = defineStore('websocket', {
  // 其他配置...
  state: () => ({
    // 这里是你的状态
    isConnect: false,
    socket: null as any,
    messageQueue: [] as Array<any>,
    readyState: 0 as number,
    socketMessage: '1' as string,
    toolOutputMsgs: '',
    currentProcessTopic: 'ready' as string,
    currentProcessPercentage: 0 as number,
    aiChatResponse: '' as string,
    isFinished: false,
  }),
  getters: {
    // 这里是你的 getters
    SET_SOCKET: (state: any, socket: any) => {
      state.socket = socket;
    },
    SET_SOCKET_MESSAGE: (state: any, socketMessage: any) => {
      state.socketMessage = socketMessage;
    },
  } as any,
  actions: {
    connectWebSocket() {
      const confirmConSuccessMessage = {
        from: storageManager.getItem('email'),
        to: 0,
        text: 'confirm',
      }; // 连接确认消息
      // const HOST_ADDRESS = `ws://172.21.213.250:7890/webSocket/${storageManager.getItem("email")}`
      const HOST_ADDRESS = `${SOCKET_IP}/dsc-systemMS/webSocket/${storageManager.getItem('email')}`;
      const socket = ref(new WebSocket(HOST_ADDRESS));
      this.socket = socket.value;
      // 监听连接事件
      socket.value.addEventListener('open', () => {
        this.isConnect = true;
        socket.value.send(JSON.stringify(confirmConSuccessMessage));
      });

      // eslint-disable-next-line unicorn/prefer-add-event-listener
      socket.value.onmessage = (event) => {
        // console.log(event.data)

        // if (message.type === 'disconnected') {
        //   ElNotification({
        //     title: message.topic,
        //     message: message.text,
        //     duration: 3000,
        //     type: 'error',
        //     offset: 58
        //   })
        //   this.socket = null
        // } else if (message.type === 'connected') {
        //   ElNotification({
        //     title: message.topic,
        //     message: message.text,
        //     duration: 3000,
        //     type: 'success',
        //     offset: 58
        //   })
        // } else {
        //   ElNotification({
        //     title: message.topic,
        //     dangerouslyUseHTMLString: true,
        //     message: `<p>${message.text}</p><a href='/home/message'>点击查看</a>`,
        //     duration: 3000,
        //     type: 'info',
        //     offset: 58
        //   })

        // }
        const message = JSON.parse(event.data);
        this.isFinished = message.isFinished;
        if (message.type === 'tool-execute') {
          if (message.text.includes('STDERR')) {
            this.toolOutputMsgs += `<br /><span style="color: red;">${message.text.replace(
              'STDERR: ',
              ' ',
            )}</span><br />`;
            return;
          }
          this.toolOutputMsgs += message.text.replace('STDOUT: ', ' ');
          // console.log(this.toolOutputMsgs)
          // console.log(message.text)
          // if (message.text.includes("STDERR")) {
          //   this.errorState = 1
          // }
          const percentageArr = message.text.match(/\d+(?=%)/g).map(Number);
          // console.log(percentageArr)
          this.currentProcessPercentage = percentageArr.pop();
          this.currentProcessTopic = message.text.replace('STDOUT: ', ' ');
          if (this.currentProcessTopic.length > 20) {
            this.currentProcessTopic = `${this.currentProcessTopic.slice(0, 20)}...`;
          }
        } else if (message.type === 'ai-chat') {
          if (this.isFinished) {
            this.aiChatResponse = '';
          } else {
            // console.log(message.text)
            this.aiChatResponse += message.text;
            // console.log(this.isFinished)
          }
        }

        // this.updateMsgQueue()
      };

      socket.value.addEventListener('close', (e) => {
        console.warn(e.code);
        this.socket = null;
        this.isConnect = false;
      });

      // 连接错误
      // eslint-disable-next-line unicorn/prefer-add-event-listener
      socket.value.onerror = (event) => {
        console.error('WebSocket error:', event);
        this.socket = null;
        this.isConnect = false;
      };
      window.addEventListener('beforeunload', () => {
        this.socket = null;
        this.isConnect = false;
      });
    },

    // 发送消息方法
    sendMessage(message: string) {
      if (this.socket?.readyState === WebSocket.CLOSED) {
        this.connectWebSocket();
      }
      this.socket.send(message);
    },

    closeWebsocket(code: number = 1000, reason: string = '') {
      this.socket.close(code, reason);
    },

    updateMsgQueue() {
      messageApi
        .getNoSentMessage(storageManager.getItem('email') as string)
        .then((res) => {
          this.messageQueue = res.data;
        });
    },
  },
});
